import {defineConfig, loadEnv} from 'vite';
import react from '@vitejs/plugin-react'
import AutoImport from 'unplugin-auto-import/vite';
import basicSsl from '@vitejs/plugin-basic-ssl';
import SRI from 'unplugin-sri/vite';
import path from 'path';
import {assetNameBuildPlugin} from './src/plugin/vite-plugin/assetNameBuildPlugin';

export default ({mode}: any) => {
    const env = loadEnv(mode, process.cwd());
    return defineConfig({
        envDir: './env',
        server: {
            port: 8086,
            host: '0.0.0.0',
            open: false,
            proxy: {
                '/api': {
                    target: env.VITE_TARGET_URL,
                    changeOrigin: true,
                    bypass(req, res, options) {
                        const url = req.url ?? '';
                        const proxyURL =
                            (options.target ?? '') +
                            (options.rewrite ? options.rewrite(url) : url);
                        console.log('真实代理地址==>', proxyURL);
                    },
                    rewrite: (path) =>
                        path.replace(
                            new RegExp(`^${env.VITE_APP_BASE_API}`),
                            `${env.VITE_APP_BASE_API}`
                        )
                },
                '/api1': {
                    target: env.VITE_APP_API,
                    // 指示代理服务器在转发请求时是否应该修改请求头中的 Host 字段。
                    changeOrigin: true,
                    rewrite: (path) => path.replace(/^\/api/, '')
                }
            }
        },
        plugins: [
            react(),
            basicSsl(),
            SRI({}),
            AutoImport({
                imports: ['react'],
                dts: 'src/types/auto-imports.d.ts'
            }),
            assetNameBuildPlugin()
        ],
        resolve: {
            alias: [
                {
                    find: '@',
                    replacement: path.resolve(__dirname, 'src/')
                }
            ]
        },
        css: {
            preprocessorOptions: {
                scss: {
                    silenceDeprecations: ['legacy-js-api']
                }
            }
        },
        build: {
            copyPublicDir: true,
            chunkSizeWarningLimit: 2600,
            minify: 'terser',
            terserOptions: {
                compress: {
                    drop_console: true,
                    drop_debugger: false
                },
                format: {
                    comments: false
                }
            }
        }
    });
};

